package com.lucy.wx.miniapp.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.rabc.domain.vo.LoginVO;
import com.lucy.rabc.entity.SysUser;
import com.lucy.rabc.service.SysUserService;
import com.lucy.wx.constant.WxMiniAppConfig;
import com.lucy.wx.miniapp.anno.WxMiniGrant;
import com.lucy.wx.miniapp.core.MiniAppOpen;
import com.lucy.wx.miniapp.core.MiniAppToken;
import com.lucy.wx.miniapp.entity.MiniAppMap;
import com.lucy.wx.miniapp.service.MiniAppMapService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @author kindear
 * 微信小程序基础应用
 */
@RestController
@RequestMapping("wx/mini")
@Api(tags = "微信小程序-核心服务")
public class MiniAppCoreController {
    @Autowired
    MiniAppToken miniAppToken;

    @Autowired
    MiniAppOpen miniAppOpen;

    @Autowired
    MiniAppMapService miniAppMapService;

    @Autowired
    SysUserService userService;

    @WxMiniGrant
    @GetMapping("token")
    @ApiOperation(value = "TOKEN查询",notes = "")
    public ResponseDTO<Object> tokenGet(){
        return ResponseDTO.succData(
                miniAppToken.get()
        );
    }

    @PostMapping("login")
    @ApiOperation(value = "小程序登录",notes = "")
    public ResponseDTO<Object> miniLogin(@RequestParam("code") String code){
        String openId = miniAppOpen.getOpenId(code);
        Optional<MiniAppMap> miniAppMapOp = miniAppMapService.getAppMap(WxMiniAppConfig.appId,openId);
        if (!miniAppMapOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未绑定账户");
        }
        MiniAppMap miniAppMap = miniAppMapOp.get();
        Long userId = miniAppMap.getUserId();
        // 获取用户ID
        Optional<SysUser> userOp = userService.getOne(userId);
        if (!userOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"关联用户不存在");
        }
        SysUser user = userOp.get();
        //执行登录
        StpUtil.login(user.getId());
        LoginVO loginVO = new LoginVO();
        BeanUtil.copyProperties(user,loginVO, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        loginVO.setToken(StpUtil.getTokenValue());
        return ResponseDTO.succData(loginVO);
    }

    @PostMapping("link")
    @ApiOperation(value = "账户关联",notes = "")
    public ResponseDTO<Object> miniLink(@RequestParam("code") String code){
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();
        String openId = miniAppOpen.getOpenId(code);
        Optional<MiniAppMap> miniAppMapOp = miniAppMapService.getAppMap(WxMiniAppConfig.appId,openId);
        if (miniAppMapOp.isPresent()){
            MiniAppMap miniAppMap = miniAppMapOp.get();
            miniAppMap.setUserId(userId);
            miniAppMapService.updateOne(miniAppMap);
        }else {
            MiniAppMap miniAppMap = new MiniAppMap();
            miniAppMap.setAppId(WxMiniAppConfig.appId);
            miniAppMap.setUserId(userId);
            miniAppMap.setOpenId(openId);
            miniAppMapService.saveOne(miniAppMap);
        }
        return ResponseDTO.succMsg("绑定成功");
    }
}
